package me.frank;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.util.Collections;
import java.util.Properties;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/10/30 14:39
 */
public class KafkaConsumerDemo2 extends Thread {
    private final KafkaConsumer consumer;

    private final String topic;

    public KafkaConsumerDemo2(String topic) {

        Properties properties=new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.10.10:9092,192.168.10.11:9092,192.168.10.12:9092");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"KafkaConsumerDemo2");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"1000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");


        consumer=new KafkaConsumer(properties);
        TopicPartition topicPartition = new TopicPartition(topic,2);
        consumer.assign(Collections.singleton(topicPartition));
       // consumer.subscribe(Collections.singleton(topic));

        this.topic=topic;
    }

    @Override
    public void run() {
        while (true) {
            ConsumerRecords<Integer,String> records = consumer.poll(1000);
            for (ConsumerRecord record:records){
                System.out.println(record.partition()+ " -> message receive: "+record.value());
            }

        }
    }

    public static void main(String[] args) {
        new KafkaConsumerDemo2("test").start();
    }
}
